package com.wind.httpProxyServer.threads;


import com.wind.httpProxyServer.constants.Properties;
import com.wind.httpProxyServer.constants.RequestMethod;
import com.wind.httpProxyServer.httpMessage.HttpRequestMessage;
import com.wind.httpProxyServer.httpMessage.exception.ConnectServerError;
import com.wind.httpProxyServer.httpMessage.startLine.RequestStartLine;
import com.wind.httpProxyServer.proxy.ClientProxy;
import com.wind.httpProxyServer.proxy.Proxy;
import com.wind.httpProxyServer.utils.SocketUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.security.NoSuchAlgorithmException;

/**
 * Http代理线程
 * 
 * @author qq
 * 
 */
public class ClientHttpProxyThread extends Thread {
	private final static Logger log = LoggerFactory.getLogger(ClientHttpProxyThread.class);

	/*
	 * 浏览器相关
	 */
	/**
	 * 浏览器Socket
	 */
	private Socket browserSocket;

	/**
	 * 浏览器输入流
	 */
	private InputStream browserInputStream;

	/*
	 * 代理服务器相关
	 */
	/**
	 * 代理服务器Socket
	 */
	private Socket proxyServerSocket;

	/*
	 * constructor
	 */
	private ClientHttpProxyThread() {
	}

	public ClientHttpProxyThread(Socket browserSocket) {
		this.browserSocket = browserSocket;
		try {
			this.browserInputStream = browserSocket.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}





	@Override
	public void run() {
		/*
		 * 解析客户端请求
		 */
		HttpRequestMessage requestMessage = null;
		try {
			//
			requestMessage = new HttpRequestMessage(browserInputStream);
			// getuserNameAndPassWorker() ;
		}
//		catch (BuildHttpMessageError e1) {
//			e1.printStackTrace();
//			SocketUtil.closeSocket(browserSocket, proxyServerSocket);
//			return;
//		}
		catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("[原始请求:]");
		System.out.print(requestMessage);
		System.out.println("----------");

		/*
		 * 连接代理服务器
		 */
		try {
			this.proxyServerSocket = SocketUtil.connectServer(Properties.ServerIp, Properties.ServerPot,
					Properties.ServerConnectTimeout);
		} catch (ConnectServerError e) {
			e.printStackTrace();
			SocketUtil.closeSocket(browserSocket, proxyServerSocket);
			return;
		}

		RequestMethod httpRequestMethod = ((RequestStartLine) requestMessage.getStartLine()).getMethod();
		System.out.println("httpRequestMethod.name():"+httpRequestMethod.name());
		if (RequestMethod.CONNECT != httpRequestMethod) { // 代理http
			try {
				this.browserSocket.setSoTimeout(Properties.ClientSoceketReadTimeout); // 设置读取浏览器Socket超时时间
				this.proxyServerSocket.setSoTimeout(Properties.ServerSocketReadTimeout); // 设置读取代理服务器Socket超时时间
			} catch (SocketException e) {
				e.printStackTrace();
			}
		}

		/*
		 * 转发流量
		 */
		Proxy proxy = new ClientProxy(browserSocket, proxyServerSocket, requestMessage);
		proxy.setEncryptRequest(true);// 客户端请求加密,服务端应解密请求
		// proxy.setDecryptResponse(true); // 解密响应
		proxy.proxy();
	}


  public void	getuserNameAndPassWorker() throws IOException, NoSuchAlgorithmException {
	  BufferedReader reader = new BufferedReader(new InputStreamReader(browserInputStream, "UTF-8"));
	  String firstLine = reader.readLine();
	  if (firstLine.startsWith("CONNECT")) {
		  // 处理 SSL/TLS 握手流程
		  String[] parts = firstLine.split("\\s+");
		  String host = parts[1].split(":")[0];
		  int port = Integer.parseInt(parts[1].split(":")[1]);
		//  SocketAddress remoteAddress = new InetSocketAddress(host, port);

		  // 以上代码用于建立 SSL/TLS 连接，请根据实际情况进行修改
		  // 此处省略 SSL/TLS 握手流程
		  SocketAddress address = new InetSocketAddress(host, port);
		  Socket socket = new Socket();
		  socket.connect(address);

		  SSLSocket sslSocket = (SSLSocket)SSLContext.getDefault().getSocketFactory().createSocket(socket, host, port, true);
		  InputStream inputStream = sslSocket.getInputStream();
		  BufferedReader reader2 = new BufferedReader(new InputStreamReader(inputStream));
		  String line = reader2.readLine();
		  while (line != null &&!line.isEmpty()) {
			  // 读取 HTTP 请求头信息，并检查是否包含 Authorization 字段
			  if (line.startsWith("Authorization: Basic ")) {
				  String encodedCredentials = line.substring(22);
				  System.out.println();
//				  String decodedCredentials = new String(Base64.getDecoder().decode(encodedCredentials), Charset.forName("UTF-8"));
//				  String[] parts2 = decodedCredentials.split(":", 2);
//				  String username = parts2[0];
//				  String password = parts2[1];
				  // 在这里使用客户端的身份验证信息进行验证
			  }
			  line = reader.readLine();
		  }
		  System.out.println();
	  } else {
		  // 处理普通的 HTTP 请求
		  StringBuilder headerBuilder = new StringBuilder(firstLine).append("\r\n");
		  String line;
		  while ((line = reader.readLine()) != null) {
			  if (line.isEmpty()) {
				  // 请求头读取完毕
				  break;
			  }
			  headerBuilder.append(line).append("\r\n");
		  }
		  String header = headerBuilder.toString();
		  // 在这里处理 HTTP 请求头
	  }

	}

}
